/**
 * JAVACC DEMO 1.0
 */
package com.apache.passport.common;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;

/**
 * description: 用于加密,目前本类中包含 BASE64,MD5,SHA以及HMAC 四种加密解密方式<br>
 * 需要注意的是,因为使用到了BASE64,此类必须使用jdk1.6.30+以上版本才可使用<br>
 * 如果低于jdk1.6.30+则需要如同Android客户端解密一样,引入sun.misc.BASE64Decoder.jar<br>
 *
 * @author Hou Dayu 创建时间：2016-5-7
 */
public class SsoEncryption {

    private static final String KEY_SHA = "SHA";

    private static final String KEY_MD5 = "MD5";

    private static SsoEncryption instance;

    private SsoEncryption() {

    }

    public static SsoEncryption getInEncryption() {
        if (null == instance) {
            instance = new SsoEncryption();
        }
        return instance;
    }

    /**
     * MAC算法可选以下多种算法
     * HmacMD5
     * HmacSHA1
     * HmacSHA256
     * HmacSHA384
     * HmacSHA512
     */
    public static final String KEY_MAC = "HmacMD5";

    /**
     * description:  BASE64解密
     *
     * @param key
     * @return
     */
    public static byte[] decryptBASE64(String key) throws Exception {
        return (new BASE64Decoder()).decodeBuffer(key);
    }

    /**
     * description:   BASE64加密
     *
     * @param key
     * @return
     */
    public static String encryptBASE64(byte[] key) throws Exception {
        return (new BASE64Encoder()).encodeBuffer(key);
    }

    /**
     * description:  MD5加密
     *
     * @param data
     * @return
     */
    public static byte[] encryptMD5(byte[] data) throws Exception {

        MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);
        md5.update(data);
        return md5.digest();
    }

    /**
     * description:  SHA加密
     *
     * @param data
     * @return
     */
    public static byte[] encryptSHA(byte[] data) throws Exception {
        MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
        sha.update(data);
        return sha.digest();
    }

    /**
     * description:  初始化HMAC密钥
     *
     * @return
     */
    public static String initMacKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);
        SecretKey secretKey = keyGenerator.generateKey();
        return encryptBASE64(secretKey.getEncoded());
    }

    /**
     * description:  HMAC加密
     *
     * @param data
     * @param key
     * @return
     */
    public static byte[] encryptHMAC(byte[] data, String key) throws Exception {
        SecretKey secretKey = new SecretKeySpec(decryptBASE64(key), KEY_MAC);
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);
        return mac.doFinal(data);
    }
}